﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TomanuExtensions;

namespace RaytracerLib.MathLib.PolynomialFunction
{
    public static class RPNToTree
    {
        public static Element Build(IEnumerable<Element> m_rpn)
        {
            Element root = BuildTree(m_rpn);
            root = TreeTransforms.Simplify(root);
            return root;
        }

        private static Element BuildTree(IEnumerable<Element> a_elements)
        {
            List<Element> elements = a_elements.ToList();

            Stack<Element> stack = new Stack<Element>();

            while (elements.Count != 0)
            {
                Element element = elements.RemoveFirst();

                if (element is SymbolElement)
                    stack.Push(element);
                else if (element is UnaryOperator)
                {
                    stack.Push((UnaryOperator)Activator.CreateInstance(element.GetType(), stack.Pop()));
                }
                else if (element is BinaryOperator)
                {
                    Element right = stack.Pop();
                    Element left = stack.Pop();
                    BinaryOperator bo = (BinaryOperator)Activator.CreateInstance(element.GetType(), left, right);
                    stack.Push(bo);
                }
            }

            if (stack.Count != 1)
                throw new FormatException();
            if (elements.Count != 0)
                throw new FormatException();

            return stack.Pop();
        }
    }
}
